package com.shitou.springai1.wx.controller;

import com.shitou.springai1.admin.service.impl.CaptchaService;
import com.shitou.springai1.wx.dto.LoginRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController // 使用@RestController确保返回JSON数据
@RequestMapping("/wx/auth")
public class ApiLoginController {

    @Autowired
    private CaptchaService captchaService;

    // 小程序登录接口
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> miniProgramLogin(
            @RequestBody LoginRequest loginRequest,
            HttpSession session) {

        Map<String, Object> result = new HashMap<>();

        // 1. 验证验证码
        String sessionCaptcha = (String) session.getAttribute("captchaCode");
        if (!loginRequest.getCaptcha().equalsIgnoreCase(sessionCaptcha)) {
            result.put("success", false);
            result.put("message", "验证码错误");
            return ResponseEntity.status(403).body(result);
        }

        // 2. 验证用户名密码（这里需要你实现具体的验证逻辑）
        boolean loginSuccess = validateUser(loginRequest.getUsername(), loginRequest.getPassword());

        if (loginSuccess) {
            // 3. 生成token（可以使用JWT等方式）
            String token = generateToken(loginRequest.getUsername());

            result.put("success", true);
            result.put("token", token);
            result.put("userInfo", getUserInfo(loginRequest.getUsername()));

            // 4. 清除已使用的验证码
            session.removeAttribute("captchaCode");

            return ResponseEntity.ok(result);
        } else {
            result.put("success", false);
            result.put("message", "用户名或密码错误");
            return ResponseEntity.status(401).body(result);
        }
    }

    // 获取验证码接口
    @GetMapping("/captcha")
    public Map<String, String> getCaptchaApi(HttpSession session) {
        CaptchaService.CaptchaResult captchaResult = captchaService.generateCaptcha();
        String captchaCode = captchaResult.getCode();
        String imageBase64 = captchaResult.getImageBase64();

        session.setAttribute("captchaCode", captchaCode);

        Map<String, String> result = new HashMap<>();
        result.put("image", imageBase64);
        return result;
    }

    // 辅助方法
    private boolean validateUser(String username, String password) {
        // 实现你的用户验证逻辑
        return true;
    }

    private String generateToken(String username) {
        // 实现token生成逻辑
        return "generated_token_" + System.currentTimeMillis();
    }

    private Map<String, Object> getUserInfo(String username) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("username", username);
        userInfo.put("nickname", "用户_" + username);
        return userInfo;
    }
}
